package com.hyf.treeview.tree;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import java.util.List;

/**
 * Created by Administrator on 2018/1/3.
 */

public abstract class TreeListViewAdapter<T> extends BaseAdapter {
    private Context mContext;
    private int defaultLevel;
    private ListView mListView;

    private List<Node> allNodes;
    private List<Node> visibleNodes;

    protected LayoutInflater mLayoutInflater;
    private OnTreeNodeClickListener mOnTreeNodeClickListener;

    public TreeListViewAdapter(Context context, ListView listView, List<T> datas, int defaultLevel) throws Exception {
        mContext = context;
        mListView = listView;
        this.defaultLevel = defaultLevel;
        mLayoutInflater = LayoutInflater.from(context);
        allNodes = TreeHelper.getSortedNodes(datas, defaultLevel);
        visibleNodes = TreeHelper.filterVisibleNodes(allNodes);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mOnTreeNodeClickListener != null) {
                    mOnTreeNodeClickListener.onItemClick(visibleNodes.get(position), position);
                }
                expandOrCollapse(position);
            }
        });
    }

    private void expandOrCollapse(int position) {
        Node node = visibleNodes.get(position);
        if (node != null) {
            if (node.isLeaf()) return;
            node.setExpand(!node.isExpand());
            visibleNodes = TreeHelper.filterVisibleNodes(allNodes);
            notifyDataSetChanged();
        }
    }

    public void setOnTreeNodeClickListener(OnTreeNodeClickListener onTreeNodeClickListener) {
        mOnTreeNodeClickListener = onTreeNodeClickListener;
    }

    @Override
    public int getCount() {
        return visibleNodes.size();
    }

    @Override
    public Object getItem(int position) {
        return visibleNodes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Node node = visibleNodes.get(position);
        View view = getConvertView(node, position, convertView, parent);
        view.setPadding(node.getLevel() * 30, 3, 3, 3);
        return view;
    }

    public abstract View getConvertView(Node node, int position, View convertView, ViewGroup parent);

    public interface OnTreeNodeClickListener {
        void onItemClick(Node node, int position);
    }
}
